package com.kaibes.module.value;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kaibes.web.api.ApiLink;
import com.kaibes.web.api.ResponseApi;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/maps")
public class KeyValueApi extends ResponseApi<KeyValue, KeyValueService> {
    
    @ApiLink(value = "列出所有键值对", validated = false)
    @GetMapping
    public ResponseEntity<List<KeyValue>> list() {
        return ResponseFactory.get(service.list(), "获取所有键值对成功", "获取所有键值对失败");
    }
    
    @ApiLink(value = "列出所有键值", validated = false)
    @GetMapping("/key")
    public ResponseEntity<List<String>> key() {
        List<KeyValue> keyValues = service.list("key");
        List<String> keyList = new ArrayList<>();
        for (KeyValue kv : keyValues) {
            keyList.add(kv.getKey());
        }
        return ResponseFactory.get(keyList, "获取所有键值成功", "获取所有键值失败");
    }
    
    @ApiLink(value = "列出所有字符串", validated = false)
    @GetMapping("/value")
    public ResponseEntity<List<String>> value() {
        List<KeyValue> keyValues = service.list("value");
        List<String> valueList = new ArrayList<>();
        for (KeyValue kv : keyValues) {
            valueList.add(kv.getValue());
        }
        return ResponseFactory.get(valueList, "获取所有字符串成功", "获取所有字符串失败");
    }
    
    @ApiLink(value = "根据key获取对应字符串", validated = false)
    @GetMapping("/{key}")
    public ResponseEntity<String> getByKey(@PathVariable String key) {
        return ResponseFactory.get(service.getValueByKey(key), "获取字符串成功", "获取字符串失败");
    }
    
    @ApiLink(value = "根据key保存对应字符串", validated = false)
    @PostMapping("/{key}")
    public ResponseEntity<String> saveByKey(@PathVariable String key, @RequestBody String value) {
        KeyValue keyValue = new KeyValue();
        keyValue.setKey(key);
        keyValue.setValue(value);
        return save(keyValue);
    }
    
    @ApiLink(value = "保存KeyValue", validated = false)
    @PostMapping
    public ResponseEntity<String> save(@RequestBody KeyValue keyValue) {
        KeyValue value = service.getByKey(keyValue.getKey());
        if (value == null) {
            service.save(keyValue);
        } else {
            service.update(keyValue);
        }
        return ResponseFactory.postSuccess(keyValue.getValue(), "保存成功！");
    }
    
}
